#include <QDebug>
#include <QMessageBox>
#include <QCloseEvent>
#include "dialogrdp.h"
#include "ui_dialogrdp.h"

DialogRDP::DialogRDP(QWidget *parent, MyTcpSocket * myTcpSocket, NetCore * netCore) :
    QDialog(parent),
    ui(new Ui::DialogRDP)
{
    ui->setupUi(this);
    this->myTcpSocket = myTcpSocket;
    this->netCore = netCore;

    // 读取配置
    config.getConfigs();
    qDebug() << config.scWidth << config.scHeight << config.indexX << config.indexY << config.bit << config.fps << config.serverPort;

    // 调整窗口大小
    resize(config.scWidth, config.scHeight);
    setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);

    //初始化图片控件
    int blockWidth = config.scWidth / config.indexX;
    int blockHeight = config.scHeight / config.indexY;
    for(int y = 0; y < config.indexY ; y ++)
    {
        for(int x = 0 ; x < config.indexX ; x ++)
        {
            QLabel * qLabel = new QLabel(this);
            qLabel->setFixedSize(blockWidth , blockHeight);
            qLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            qLabel->setText(QString("[%1 , %2]").arg(y).arg(x));
            qLabel->move(x * blockWidth , y * blockHeight);
            qLabel->show();
            qLabelList.append(qLabel);
        }
    }

    // 绑定数据传输信号
    connect(netCore, &NetCore::sigScData, this, &DialogRDP::on_screen_data);
    //绑定客户端变化信号
    connect(netCore, &NetCore::sigClient, this, &DialogRDP::on_client);

    // 下发屏幕配置信息到客户端
    netCore->scConfigRequest(myTcpSocket, &config);
}

DialogRDP::~DialogRDP()
{
    disconnect(netCore, &NetCore::sigScData, this, &DialogRDP::on_screen_data);
    disconnect(netCore, &NetCore::sigClient, this, &DialogRDP::on_client);
    delete ui;
}

// ***********************  以下是网络通讯槽函数 *****************************

void DialogRDP::on_screen_data(MyTcpSocket* tcpSocket, int x, int y, QByteArray data)
{
    if(myTcpSocket == tcpSocket)
    {
        qDebug() << "收到分块图片" << x << y;
        QPixmap pixmap;
        pixmap.loadFromData(data, "png");
        setQLabelPixmap(pixmap, x, y);
    }
}

void DialogRDP::on_client(int code, MyTcpSocket * myTcpSocket)
{
    // 只关注客户端断开消息，断开就把socket句柄设置为null
    if(code == CLI_DEL)
    {
        if(myTcpSocket == this->myTcpSocket)
        {
            this->myTcpSocket = nullptr;
        }
    }
}

// ***********************  以下窗口私有函数 ***************************
void DialogRDP::setQLabelPixmap(QPixmap pixmap, int x, int y)
{
    if(config.indexX * y + x < qLabelList.size())
    {
        qLabelList.at(config.indexX * y + x)->setPixmap(pixmap);
    }
}

// ***********************  以下窗口重载函数 ***************************
// 关闭窗口消息重载
void DialogRDP::closeEvent(QCloseEvent *e)
{
    // 通知客户都停止抓图发包
    netCore->scSigRequest(myTcpSocket, 1);

    e->accept();
}
